package com.woniu51.user.service.impl;

import com.woniu.common.constant.UserConstants;
import com.woniu.common.core.redis.RedisCache;
import com.woniu51.entity.UnauthUrl;
import com.woniu51.user.mapper.UnAuthUrlMapper;
import com.woniu51.user.service.UnAuthService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 杨光
 * @date 2022年04月01日 10:08
 */
@Service
public class UnAuthServiceImpl implements UnAuthService {

    @Autowired
    private UnAuthUrlMapper unAuthUrlMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    //在spring启动过程中，执行初始化的方法，把数据库中的url列表放入redis
    @PostConstruct//加了这个注解的方法，spring在启动过程中就会执行这个方法
    public void initUnauthUrlList(){

        //删除redis中的列表
        redisCache.deleteObject(UserConstants.REDIS_UNAUTH_URL_PREFIX);
        //从数据库读取url列表
        List<String> urlList = unAuthUrlMapper.selectAll().stream().map(s -> {
            return s.getUrl();
        }).collect(Collectors.toList());
        //把url列表放入redis
        redisCache.setCacheList(UserConstants.REDIS_UNAUTH_URL_PREFIX,urlList);

    }


    @Override
    public List<UnauthUrl> list(UnauthUrl unauthUrl) {
        return unAuthUrlMapper.select(unauthUrl);
    }

    @Override
    public UnauthUrl getById(Integer id) {
        return unAuthUrlMapper.selectByPrimaryKey(id);
    }

    @Override
    public int add(UnauthUrl unauthUrl) {
        int result = unAuthUrlMapper.insertSelective(unauthUrl);

        initUnauthUrlList();

        //发消息给rabbitmq，通知网关
        sendMsg();

        return result;
    }

    @Override
    public int edit(UnauthUrl unauthUrl) {
        int result =  unAuthUrlMapper.updateByPrimaryKeySelective(unauthUrl);

        initUnauthUrlList();

        //发消息给rabbitmq，通知网关
        sendMsg();

        return result;
    }

    @Override
    public int remove(Integer[] ids) {
        List<Integer> idList = Arrays.stream(ids).collect(Collectors.toList());
        int result =  unAuthUrlMapper.deleteByIdList(idList);

        //刷新redis
        initUnauthUrlList();

        //发消息给rabbitmq，通知网关
        sendMsg();

        return result;
    }


    private void sendMsg(){

        rabbitTemplate.convertAndSend(UserConstants.MQ_REFRESH_UNAUTH_URL_EXCHANGE,
                UserConstants.MQ_REFRESH_UNAUTH_URL_ROUTING_KEY,
                "refreshRedis");
    }

}
